package com.zretc.letter.service;

import com.zretc.common.encoder.WebServerEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/webSocket",encoders = WebServerEncoder.class)
@Slf4j
public class WebSocketServer {
    private Session session;
    private String wid;
        private static ConcurrentHashMap<String,WebSocketServer> webSocketServersMap=new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session)
    {
        this.session=session;
        this.wid=session.getId();
        webSocketServersMap.put(session.getId(),this);
        System.out.println(webSocketServersMap.size()+"wid:"+wid);
    }
    @OnClose
    public void onClose()
    {
        webSocketServersMap.remove(this.wid);
    }
    @OnMessage
    public void onMessage(String msg)
    {
        log.info(msg);
    }
    public static void sendMessage(Object obj)
    {
        webSocketServersMap.forEach((s,v) -> {
            try {
                v.session.getBasicRemote().sendObject(obj);
                System.out.println("我已经走到这了");
            } catch (IOException | EncodeException e) {
               log.error(e.getMessage());
            }
        });
    }
}
